package com.woniuxy.interceptor;

import com.alibaba.fastjson.JSON;
import com.woniuxy.util.ResponseData;
import com.woniuxy.util.ResponseEnum;
import org.redisson.api.RBloomFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @BelongsProject: pigTrotterStore
 * @BelongsPackage: com.woniuxy.interceptor
 * @Author: Quan
 * @Date: 2025/3/13 8:23
 */
@Component
public class BloomFilterInterceptor implements HandlerInterceptor {
	@Autowired
	private RBloomFilter<String> bloomFilter;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String jsonString = JSON.toJSONString(ResponseData.fail(ResponseEnum.DETAIL_ERROR));

		Map<String, Object> pathVariable = (Map<String, Object>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
		if (pathVariable == null) {
			response.getWriter().print(jsonString);
			return false;
		}

		String id = (String) pathVariable.get("id");
		if (!bloomFilter.contains(id)) {
			response.getWriter().print(jsonString);
			return false;
		}

		return true;
	}
}
